package com.demo.kafka;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author wangfengchen
 */
@Slf4j
@RestController
@RequestMapping("/kafka")
public class KafkaController {


  @Autowired
  private KafkaTemplate<String, String> kafkaTemplate;

  /**
   * 生产消息
   * @param msg
   * @return
   */
  @GetMapping("/sendKafka")
    public boolean sendTopic(@RequestParam String msg){
    ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("kafkaTopic", msg);
    future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
      @Override public void onFailure(Throwable ex) {
        log.error("kafka发送消息失败，e = {}", ExceptionUtils.getStackTrace(ex));
      }

      @Override public void onSuccess(SendResult<String, String> result) {
        log.info("kafka发送消息成功，result = {}", result);
      }
    });
    return true;
    }

}